﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using DailyPoetryM.Models;
using DailyPoetryM.Services;
using System.Linq.Expressions;
using TheSalLab.MauiInfiniteScrolling;

namespace DailyPoetryM.ViewModels;

public class ResultPageViewModel : ObservableObject
{
    private bool _canLoadMore;
    public const int PageSize = 20;
    public const string Loading = "正在载入";
    public const string NoResult = "没有满足条件的结果";
    public const string NoMoreResult = "没有更多结果";
    private readonly IPoetryStorage poetryStorage;
    private Expression<Func<Poetry, bool>>? _where;
    public Expression<Func<Poetry,bool>> Where
    {
        get => _where;
        set => _canLoadMore = SetProperty(ref _where,value);
    }

    private string _status;

    public string Status
    {
        get { return _status; }
        set { SetProperty(ref _status, value); }
    }
    public MauiInfiniteScrollCollection<Poetry> Poetries { get; }

    public ResultPageViewModel(IPoetryStorage poetryStorage)
    {
        this.poetryStorage = poetryStorage;
        //TODO 测试用，正式版需要删除
        Where = Expression.Lambda<Func<Poetry, bool>>(
            Expression.Constant(true),
            Expression.Parameter(typeof(Poetry), "p")
            );

        Poetries = new MauiInfiniteScrollCollection<Poetry>
        {
            OnCanLoadMore = () => _canLoadMore,
            OnLoadMore = async () =>
            {
                Status = Loading;
                var poetries = (await poetryStorage.GetPoetriesAsync(Where,
                    Poetries.Count, PageSize)).ToList();
                Status = string.Empty;

                if (poetries.Count < PageSize)
                {
                    _canLoadMore = false;
                    Status = NoMoreResult;
                }

                if (Poetries.Count == 0 && poetries.Count == 0)
                {
                    _canLoadMore = false;
                    Status = NoResult;
                }

                return poetries;
            }
        };
        _lazyNavigatedToCommand = new Lazy<AsyncRelayCommand>(()=> 
        new AsyncRelayCommand(NavigatedToCommandFunction));       
    }

    private Lazy<AsyncRelayCommand>  _lazyNavigatedToCommand;
    public AsyncRelayCommand NavigatedToCommand => _lazyNavigatedToCommand.Value;

    public async Task NavigatedToCommandFunction()
    {
        await poetryStorage.InitializeAsync();
        Poetries.Clear();
        await Poetries.LoadMoreAsync();
    }
}
